import type {MenuItem, MenuTreeItem} from "@/type/common/MenuRouter";

// 构建树形结构函数
export const buildMenuTree = (menus: MenuItem[]): MenuTreeItem[] => {
    const tree: MenuTreeItem[] = []
    const menuMap: Record<string, MenuTreeItem> = {}

    // 先创建所有节点的映射
    menus.forEach((menu) => {
        menuMap[menu.id] = {...menu, children: []}
    })

    // 构建树形结构
    menus.forEach((menu) => {
        if (menu.parentId) {
            if (menuMap[menu.parentId]) {
                menuMap[menu.parentId].children?.push(menuMap[menu.id])
            }
        } else {
            tree.push(menuMap[menu.id])
        }
    })

    // 对每个节点的子节点按orderNum排序
    const sortChildren = (nodes: MenuTreeItem[]) => {
        nodes.forEach((node) => {
            if (node.children && node.children.length > 0) {
                node.children.sort((a, b) => a.orderNum - b.orderNum)
                sortChildren(node.children)
            }
        })
    }

    // 对根节点排序
    tree.sort((a, b) => a.orderNum - b.orderNum)
    sortChildren(tree)

    return tree
}